package doc.jmidifile;

import java.io.BufferedOutputStream;
import java.io.IOException;
import java.io.Serializable;
import java.security.InvalidParameterException;
import java.util.Arrays;

final class JMidiHead extends JMidiChunk implements Serializable {
    public static final int SINGLE_TRACK_FORMAT = 0;
    public static final int COMMON_META_TRACK_FORMAT = 1;
    public static final int UNSUPPORTED_FORMAT = 2;

    final int format;
    final int trackCount;
    final int tpq;

    JMidiHead(final byte[] data, int[] off) throws InvalidParameterException {
        super(data, off);
        // 检测文件头
        if (!Arrays.equals(HEAD_ID, this.id)) {
            makeInvalidMidiFileException();
        }
        int offset = off[0];
        if ((data.length - offset) < 6) {
            makeInvalidMidiFileException();
        }
        // 判定文件格式是否支持
        format = bytesToInt(data, offset, 2);
        if (format == UNSUPPORTED_FORMAT) {
            throw new InvalidParameterException("midi file format " + UNSUPPORTED_FORMAT + " is not supported");
        }
        offset += 2;

        // 获取音轨数量和 tpq
        trackCount = bytesToInt(data, offset, 2);
        offset += 2;
        tpq = bytesToInt(data, offset, 2);
        offset += 2;

        off[0] = offset;
    }

    JMidiHead(int format, int trackCount, int tpq) {
        super(HEAD_ID, 6);
        this.format = format;
        this.trackCount = trackCount;
        this.tpq = tpq;
    }

    void save(BufferedOutputStream stream) throws IOException {
        super.save(stream);
        byte[] buf = new byte[2];
        stream.write(intToBytes(format, buf));
        stream.write(intToBytes(trackCount, buf));
        stream.write(intToBytes(tpq, buf));
    }
}


